package se.topshelf.golftracker.web.controller.course;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import se.topshelf.golftracker.core.domain.Course;
import se.topshelf.golftracker.core.domain.MemberClub;
import se.topshelf.golftracker.core.service.BaseService;
import se.topshelf.golftracker.core.service.CourseService;
import se.topshelf.golftracker.core.service.MemberClubService;
import se.topshelf.golftracker.web.validator.BaseEntityValidator;

import java.text.MessageFormat;

/**
 *  Validates Course entities, so that they are ok save.
 */
public class CourseValidator extends BaseEntityValidator<Course> {
    static final String NAME_FIELD_NAME = "name";
    public static final String MEMBER_CLUB_FIELD_NAME = "memberClub";
    private CourseService courseService;


    public CourseValidator(CourseService courseService) {
        super(Course.class);
        this.courseService = courseService;
    }


    @Override
    protected void validateFields(Course entityToCheck, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, NAME_FIELD_NAME, REQUIRED_ERROR_CODE, REQUIRED_ERROR_DEFAULT_MESSAGE);
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, MEMBER_CLUB_FIELD_NAME, REQUIRED_ERROR_CODE, REQUIRED_ERROR_DEFAULT_MESSAGE);
    }

    @Override
    protected BaseService getBaseService() {
        return courseService;
    }

    @Override
    protected boolean isNaturalKeyEqual(Course savedEntity, Course entityToCheck) {
        return savedEntity.getName().equals(entityToCheck.getName()) && savedEntity.getMemberClub().equals(entityToCheck.getMemberClub());
    }

    @Override
    protected void doRejectOfNaturalField(Errors errors, Course entityToCheck) {
        errors.rejectValue(NAME_FIELD_NAME, "duplicate",
                MessageFormat.format("Duplicate course",
                        entityToCheck.getName()));
    }
}
